import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true,
        secure: false,
        ws: true,
        headers: {
          "Access-Control-Allow-Origin": "*",
        },
      },
      "/amap": {
        target: "https://restapi.amap.com",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/amap/, ''),
        headers: {
          "Access-Control-Allow-Origin": "*",
        },
      },
      "/ws": {
        target: "wss://www.buaa.fun",  // 直接代理到正确的服务器
        changeOrigin: true,
        secure: false,
        ws: true,
        rewrite: (path) => path.replace(/^\/ws/, '/api/channel'), // 将/ws重写为/api/channel
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('🔴 WebSocket代理错误:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('🔌 WebSocket代理请求:', req.url);
          });
          proxy.on('open', () => {
            console.log('✅ WebSocket代理连接已建立');
          });
          proxy.on('close', () => {
            console.log('🔌 WebSocket代理连接已关闭');
          });
        },
      },
      "/blm": {
        target: "https://www.buaa.fun",
        changeOrigin: true,
        secure: false,
        headers: {
          "Access-Control-Allow-Origin": "*",
          Referer: "https://www.buaa.fun",
        },
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('🔴 BLM代理错误:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('🖼️ 代理图片请求:', req.url);
          });
        },
      },
    },
    hmr: {
      overlay: false, // 禁用错误覆盖层
    },
    watch: {
      usePolling: true, // 使用轮询方式监听文件变化
    },
  },
});